import { useEffect, useRef } from 'react'
import './DelWatermarkModal.scss'
import RemoveSvg from '@/svg/RemoveSvg'
import useStateRef from '@/hooks/useStateRef'
import imageLoadManager from '@/lib/imageLoadManager'
import { loadImageInfo } from '@/utils/loadVideo'
import { showLoading } from '@/utils/loading'
import { imageFilter } from '@/lib/imageFilter'
import CustomCanvas from '@/component/CustomCanvas'
import DeleteSvg from '@/svg/DeleteSvg'
import { useI18n } from '@/i18n'
interface Props {
  show: boolean
  onHide: () => void
  frameList: FrameInfo[]
  allFrameList: FrameInfo[]
  fps: number
  onUpdate: (frameList: FrameInfo[]) => void
}

const DelWatermarkModal = ({
  show,
  onHide,
  frameList,
  allFrameList,
  fps,
  onUpdate,
}: Props) => {
  const { t } = useI18n()
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const imageFrameList = useRef<HTMLImageElement[]>([])
  const canvasCtx = useRef<CanvasRenderingContext2D | null>(null)
  const [canvasSize, setCanvasSize, canvasSizeRef] = useStateRef({
    width: 200,
    height: 200,
  })
  const [fillList, setFillList, fillListRef] = useStateRef<
    {
      rect: Rect
      color: string
    }[]
  >([])
  const [canvasRealSize, setCanvasRealSize, canvasRealSizeRef] = useStateRef({
    width: 200,
    height: 200,
  })
  const canvasScale = {
    width: canvasRealSizeRef.current.width / canvasSizeRef.current.width,
    height: canvasRealSizeRef.current.height / canvasSizeRef.current.height,
  }
  useEffect(() => {
    const observer = new ResizeObserver(handleResize)
    function handleResize() {
      setCanvasRealSize({
        width: canvasRef.current.clientWidth,
        height: canvasRef.current.clientHeight,
      })
    }
    const canvas = canvasRef.current
    handleResize()
    canvas && observer.observe(canvas)
    return () => {
      observer.unobserve(canvas)
      observer.disconnect()
    }
  }, [])
  useEffect(() => {
    const task = async () => {
      setFillList([])
      if (frameList.length != 0) {
        const info = await loadImageInfo(frameList[0].url)
        setCanvasSize({
          width: info.width,
          height: info.height,
        })
        canvasRef.current.width = info.width
        canvasRef.current.height = info.height
      } else {
        setCanvasSize({ width: 200, height: 200 })
        canvasRef.current.width = 200
        canvasRef.current.height = 200
      }
    }
    task()
  }, [frameList])
  useEffect(() => {
    if (!show) {
      return
    }
    let isEnd = false
    const task = async () => {
      imageFrameList.current = await imageLoadManager.loadImageList(frameList)
      //   if (!play) {
      //     return
      //   }
      // 帧时间
      const frameTime = 1000 / fps
      let frame = 0
      let nowframeTime = 0
      let lastTime = 0
      canvasCtx.current = canvasRef.current.getContext('2d')
      canvasCtx.current.imageSmoothingEnabled = false
      const anim = (nowTime: number) => {
        const deltaTime = nowTime - lastTime
        lastTime = nowTime
        nowframeTime += deltaTime
        const addFrame = Math.floor(nowframeTime / frameTime)
        nowframeTime = nowframeTime % frameTime
        draw(frame)
        frame += addFrame
        if (frameList.length == 0) isEnd = true
        while (frame >= frameList.length && frameList.length != 0) {
          frame -= frameList.length
        }
        if (isEnd) return
        requestAnimationFrame(anim)
      }
      requestAnimationFrame(anim)
    }
    task()
    return () => {
      isEnd = true
    }
  }, [show, frameList, canvasSize])

  const draw = (frame = 0) => {
    if (frame < 0 || frame >= imageFrameList.current.length) {
      return
    }
    const ctx = canvasCtx.current
    if (!ctx) return
    const w = canvasSizeRef.current.width
    const h = canvasSizeRef.current.height
    ctx.clearRect(0, 0, w, h)
    if (frameList.length == 0) {
      return
    }
    const imageW = imageFrameList.current[frame].naturalWidth
    const imageH = imageFrameList.current[frame].naturalHeight
    ctx.drawImage(
      imageFrameList.current[frame],
      0,
      0,
      imageW,
      imageH,
      0,
      0,
      w,
      h
    )
    filter(ctx)
    // 绘制拖动rect
    //
    if (dragRect.current.drag) {
      const rect = dragRect.current
      const x = Math.min(rect.startPos.x, rect.lastPos.x)
      const y = Math.min(rect.startPos.y, rect.lastPos.y)
      const w = Math.abs(rect.startPos.x - rect.lastPos.x)
      const h = Math.abs(rect.startPos.y - rect.lastPos.y)
      const color = colorRef.current
      ctx.fillStyle = color
      ctx.fillRect(x, y, w, h)
    }
  }
  const filter = (ctx: CanvasRenderingContext2D) => {
    // 绘制覆盖区域
    fillListRef.current.forEach((item) => {
      console.log(1)

      const rect = item.rect
      const color = item.color
      ctx.fillStyle = color
      ctx.fillRect(
        rect.left,
        rect.top,
        rect.right - rect.left,
        rect.bottom - rect.top
      )
    })
  }

  async function onSave(): Promise<void> {
    const hideloading = showLoading(t('processing'))
    try {
      const res = await imageFilter(
        allFrameList,
        canvasRef.current.width,
        canvasRef.current.height,
        (ctx, cur) => {
          filter(ctx)
          hideloading.setProgress((cur / allFrameList.length) * 100)
        }
      )
      onUpdate(res)
    } catch (e) {
      console.error(e)
    } finally {
      hideloading()
    }
  }
  const dragRect = useRef({
    startPos: {
      x: 0,
      y: 0,
    },
    lastPos: {
      x: 0,
      y: 0,
    },
    drag: false,
  })
  const [color, setColor, colorRef] = useStateRef('#00ff00')
  return (
    <div className="DelWatermarkModal-component">
      <div className={`DelWatermarkModal ${show ? 'show' : ''}`}>
        <div className="top">
          <div className="title">
            <span>{t('regionalCoverage')}</span>
          </div>
          <ripple-button className="remove" onClick={onHide}>
            <RemoveSvg />
          </ripple-button>
        </div>
        <div className="center-box">
          <div className="cont-box">
            <div className="canvas-view">
              <CustomCanvas
                onMouseDown={(e) => {
                  const pos = getCanvasMousePosition(e, canvasRef.current)
                  dragRect.current.drag = true
                  dragRect.current.startPos = pos
                  dragRect.current.lastPos = pos
                  const onMouseMove = (e: MouseEvent) => {
                    const pos = getCanvasMousePosition(e, canvasRef.current)
                    dragRect.current.lastPos = pos
                  }
                  window.addEventListener('mousemove', onMouseMove)
                  window.addEventListener(
                    'mouseup',
                    () => {
                      window.removeEventListener('mousemove', onMouseMove)

                      dragRect.current.drag = false
                      const rect = getRect(
                        dragRect.current.startPos,
                        dragRect.current.lastPos
                      )
                      if (rect.left == rect.right || rect.top == rect.bottom) {
                        return
                      }
                      setFillList((list) => {
                        return [...list, { rect, color }]
                      })
                    },
                    { once: true }
                  )
                }}
                className="canvas"
                ref={canvasRef}></CustomCanvas>
            </div>
            <div className="list">
              <div className="list-inner">
                {fillList.map((item, index) => {
                  return (
                    <div className="item" key={index}>
                      <div className="label">
                        {t('rect')}
                        {index + 1}:{item.color}
                      </div>
                      <ripple-button
                        className="clear"
                        onClick={() => {
                          const list = fillList
                          list.splice(index, 1)
                          setFillList([...list])
                        }}>
                        <DeleteSvg />
                      </ripple-button>
                    </div>
                  )
                })}
                {fillList.length == 0 && (
                  <div className="empty">
                    {t('No coverage area currently available')}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="input-box">
            <div className="label">
              <label>{t('coverColor')}</label>
            </div>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 5,
              }}>
              <ripple-button
                className="color-input"
                onClick={async () => {
                  // @ts-ignore
                  const eyeDropper = new EyeDropper()
                  const value = await eyeDropper.open()
                  setColor(value.sRGBHex)
                }}
                style={{
                  background: color,
                }}></ripple-button>
              <span>#</span>

              <input
                type="text"
                className="input"
                value={color.substring(1)}
                onChange={(e) => {
                  let value = e.target.value
                  value = value.replace(/[^0-9a-fA-F]/g, '')
                  if (value.length > 6) {
                    value = value.substring(0, 6)
                  }
                  setColor(`#${value}`)
                }}
              />
            </div>
          </div>
        </div>
        <ripple-button
          style={{
            marginLeft: 'auto',
            background: 'var(--primary-color)',
            color: 'white',
            width: 'fit-content',
            padding: '8px 10px',
          }}
          onClick={onSave}>
          {t('saveChanges')}
        </ripple-button>
      </div>
      <div className={`mask ${show ? 'show' : ''}`} onClick={onHide}></div>
    </div>
  )
}

function getCanvasMousePosition(
  event: { clientX: number; clientY: number },
  canvas: HTMLCanvasElement
) {
  // 获取Canvas的实际显示尺寸和位置
  const rect = canvas.getBoundingClientRect()

  // 计算鼠标在页面中的位置相对于Canvas的位置
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  // 考虑Canvas的实际渲染尺寸与显示尺寸的比例
  const scaleX = canvas.width / rect.width
  const scaleY = canvas.height / rect.height

  // 返回缩放后的坐标
  return {
    x: x * scaleX,
    y: y * scaleY,
  }
}
function getRect(
  startPos: { x: number; y: number },
  lastPos: { x: number; y: number }
) {
  const left = Math.min(startPos.x, lastPos.x)
  const top = Math.min(startPos.y, lastPos.y)
  const width = Math.abs(startPos.x - lastPos.x)
  const height = Math.abs(startPos.y - lastPos.y)
  return { left, top, right: left + width, bottom: top + height }
}
export default DelWatermarkModal
